package org.egedede.simulation.ui.desktop.swing;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.SwingWorker;
import javax.swing.text.JTextComponent;

import org.egedede.simulation.managers.SimulationManager;
import org.egedede.simulation.model.Simulation;

/**
 * This action intends to run a simulation a fixed number of time.
 */
public class RunMultiTimesAction extends AbstractAction {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = -9102811555749067943L;

	/** The manager. */
	private SimulationManager manager;

	/** The simulation. */
	private Simulation simulation;

	/** The ui manager. */
	private JTextComponent textComponent;

	/** The container. */
	private ModelContainer container;

	/**
	 * (non-Javadoc)
	 * 
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 * @param e
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		SwingWorker<Object,Object> worker = new SwingWorker<Object,Object>(){

			@Override
			protected Object doInBackground() throws Exception {
				boolean canContinue = RunMultiTimesAction.this.container.canContinue();
				int nbTimes = Integer.parseInt(RunMultiTimesAction.this.textComponent.getText().trim());
				for (int i = 0; i < nbTimes && canContinue; i++) {
					canContinue = RunMultiTimesAction.this.manager.nextStep(RunMultiTimesAction.this.simulation);
					RunMultiTimesAction.this.container.setCanContinue(canContinue);
					RunMultiTimesAction.this.container.modelHasChanged();
					Thread.sleep(100);
				}

				return null;
			}
			
		};
		worker.execute();

	}

	/**
	 * Setted by spring.
	 * 
	 * @param manager
	 *            the simulation manager
	 */
	public void setManager(SimulationManager manager) {
		this.manager = manager;
	}

	/**
	 * Setted by spring.
	 * 
	 * @param manager
	 *            the simulation manager
	 */
	public void setSimulation(Simulation manager) {
		this.simulation = manager;
	}

	/**
	 * Setted by Spring.
	 * 
	 * @param textComponent
	 *            the text component giving the number of simulation todo
	 */
	public void setTextComponent(JTextComponent textComponent) {
		this.textComponent = textComponent;
	}

	/**
	 * Setted by spring.
	 * 
	 * @param manager
	 *            the simulation manager
	 */
	public void setContainer(ModelContainer manager) {
		this.container = manager;
	}

	/**
	 * Instantiates a new run multi times action.
	 */
	public RunMultiTimesAction() {
		super("Run");
	}

}
